const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 生成指定长度的随机字符串
function generateCardNo(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

// 生成卡密
async function generateCards() {
    try {
        const batchNo = new Date().getTime().toString();
        const cards = [];
        
        // 生成不同类型的卡密
        const cardTypes = [
            { memberType: 1, days: 7, count: 5 },   // 7天会员
            { memberType: 2, days: 30, count: 3 },  // 30天会员
            { memberType: 3, days: 365, count: 2 }  // 365天会员
        ];

        for (const type of cardTypes) {
            for (let i = 0; i < type.count; i++) {
                const cardNo = generateCardNo(12); // 生成12位卡密
                cards.push({
                    cardNo,
                    memberType: type.memberType,
                    days: type.days,
                    status: 0, // 未使用
                    batchNo,
                    expireTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30天后过期
                });
            }
        }

        // 批量创建卡密
        const result = await prisma.card.createMany({
            data: cards,
            skipDuplicates: true
        });

        console.log(`Successfully generated ${result.count} cards with batch number: ${batchNo}`);
        
        // 查询并显示生成的卡密
        const generatedCards = await prisma.card.findMany({
            where: { batchNo },
            select: {
                cardNo: true,
                memberType: true,
                days: true,
                expireTime: true
            }
        });

        console.log('\nGenerated cards:');
        generatedCards.forEach(card => {
            console.log(`Card No: ${card.cardNo}, Type: ${card.memberType} (${card.days} days)`);
        });

    } catch (error) {
        console.error('Error generating cards:', error);
    } finally {
        await prisma.$disconnect();
    }
}

// 执行生成
generateCards(); 